#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os.path
import re
import tornado.database
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
import base64
import hashlib
import basehandler
import Image

from datetime import datetime

# Business Handler
class BusinessHandler(basehandler.BaseHandler):
    def __init__(self,a,r,**k):
        basehandler.BaseHandler.__init__(self,a,r,**k)
        self.allow(1)

    def get(self,args):
        
        # debug truncate tables
        if "items/truncate" == args:
            tables = ['tags_rel','attachments','attachments_rel','items','rating']
            for table in tables:
                self.db.execute("truncate %s",table)
            self.redirect("/business/items")
            self.finish()
            
        if args:
            v = {}
            if 'items' == args:v = self.tags("show")
            if 'items/list' == args:v['items'] = self.items("show")
            self.render("business_"+args.replace("/","_")+".html",val=v)
        else:
            v = {}
            v['items'] = self.items("show")
            self.render("business_items_list.html",val=v)

    def post(self,args):
        if "items/add" == args:
            self.items("add")
            self.redirect("/business/items")
        if "items/del" == args:
            self.items("del")
            self.finish()
        

    def items(self,action):
        """ 添加
        """
        if action=='add':
            lastid = self.db.execute("insert into items(`uid`,`name`) values(%s,%s)",self.get_secure_cookie("uid"),self.get_argument("name"))
            if lastid:
                # upload
                if self.request.files:
                    pic = self.request.files['pic'][0]
                    _ename = hashlib.md5(str(self.uid)+pic['filename']).hexdigest()
                    rname = str(self.uid)+"_"+pic['filename']
                    rpath = './static/attachments/raw/'+rname
                    file(rpath,'w').write(pic['body'])

                    im = Image.open(rpath)
                    ename = _ename+"."+im.format
                    resize = 800,800
                    im.thumbnail(resize)
                    im.save("./static/attachments/resize_"+ename,im.format)
            
                    size = 200,150
                    im.thumbnail(size)
                    im.save("./static/attachments/thumb_"+ename,im.format)

                    # insert to attachments
                    aid = self.db.execute("insert into attachments(`rname`,`ename`) values(%s,%s)",rname,ename)

                    # insert to  attchments_rel
                    arid = self.db.execute("insert into attachments_rel(`iid`,`aid`) values(%s,%s)",lastid,aid)
                    
                # tags_rel
                rel_param =[]
                for tid,val in enumerate(self.get_argument("tags").split(":")):
                    if val:
                        rel_param.append((lastid,tid))
                self.db.executemany("insert into tags_rel(`iid`,`tid`) values(%s,%s)",rel_param)

                # rating
                today = datetime.utcnow()
                self.db.execute("insert into rating(`iid`,`datetime`) values(%s,%s)",lastid,str(today).split(".")[0])
                    
                print "done!"
            else:
                print "failed!"
                
        elif action=="show":
            res = self.db.query("select i.*,r.*,a.ename from items as i left join rating as r on i.id=r.iid left join attachments_rel as ar on i.id=ar.iid and ar.type=0 left join attachments as a on ar.aid=a.id where i.uid=%s and i.delete = 0 order by r.datetime desc",self.uid)
            return res

        elif action=="del":
            self.write("return success!");

    def tags(self,action):
        """ 标签动作集
        """
        if action == "show":
            val = {}
            val['tags_type'] = ['其它','菜系','口味','材料','功效','配置']
            val['tags_set'] = self.db.query("select * from tags where `delete`=0")
            return val
